'use strict';
const db = uniCloud.database();
const dbCmd = db.command
const $ = db.command.aggregate
const tools = require("../../tools/index.js")
const alioss = require('../../oss/index.js')
const Encryption_decryption = require('../../JSEncrypt/index.js')

const qdRouter = require('./qdRouter.js')

// 同步路由配置表（包裹增删改）
exports.SyncRouter = async (body_data)=>{
	let ReturnData = {code:200,msg:"参数错误！"}
	// 分为一级添加和二级添加
	let {id,data} = body_data
	
	data ? delete data._id :""  // doc后是不能存在有_id这个字段
	// 一般是更新一个文档的数据或者children的数据
	if(id && data){
		let addRes = await db.collection('admin-router').doc(id).update(data)
		return {
			code:200,
			msg:'操作成功~'
		}
	// 一般用于添加根路由
	}else if(!id && data){
		// 添加新的根
		let addRes = await db.collection('admin-router').add(data)
		return {
			code:200,
			msg:'操作成功~'
		}
	// 一般用于删除根路由
	}else if(id && !data){
		let removeRes = await db.collection('admin-router').doc(id).remove()
		return {
			code:200,
			msg:'操作成功~'
		}
	}else{
		return ReturnData
	}
}

// 查看路由表
exports.SelRouter = async(body_data)=>{
	let ReturnData = {code:200,msg:"参数错误！"}
	let {RouterList} = body_data
	
	let res = await db.collection('admin-router').get()
	ReturnData.msg='查询成功'
	ReturnData.data = res.data
	return ReturnData
}

// 添加角色权限的接口
exports.AddRole = async(body_data)=>{
	let ReturnData = {code:200,msg:"参数错误！"}
	let {RoleName,RoleDescript,RouterList} = body_data
	let AddRole = await db.collection('admin-role').add({
		RoleName,RoleDescript,RouterList
	})
	if(AddRole.id){
		ReturnData.msg='添加成功~'
		return ReturnData
	}else{
		ReturnData.code = 200
		ReturnData.msg = '内部错误~'
	}
}

// 获取角色信息
exports.GetRoleInfo = async (body_data)=>{
	let ReturnData = {code:200,msg:"参数错误！"}
	let {_id} = body_data
	try{
		// 查询单个
		if(_id){
			let SelRoleInfo = await db.collection('admin-role').doc(_id).get()
			ReturnData.data = SelRoleInfo.data[0]
			ReturnData.msg='查询成功~'
			return ReturnData
		}else{
			// 查询全部
			let SelRoleInfo = await db.collection('admin-role').get()
			ReturnData.data = SelRoleInfo.data
			ReturnData.msg='查询成功~'
			return ReturnData
		}
	}catch(e){
		ReturnData.code=500
		ReturnData.msg='服务器错误~'
		return ReturnData
	}
}

// 修改角色信息
exports.UpdRole = async (body_data)=>{
	let ReturnData = {code:200,msg:"参数错误！"}
	let {_id,RoleName,RoleDescript,RouterList} = body_data
	if(!_id || !RoleName) return ReturnData
	
	try{
		let UpdRoleInfo = await db.collection('admin-role').doc(_id).update({
			RoleName,RoleDescript,RouterList
		})
		ReturnData.msg='修改成功~'
		return ReturnData
	}catch(e){
		ReturnData.code=500
		ReturnData.msg='服务器错误~'
		return ReturnData
	}
}

// 删除角色信息
exports.DelRole = async (body_data)=>{
	let ReturnData = {code:200,msg:"参数错误！"}
	let {_id} = body_data
	if(!_id) return ReturnData
	
	try{
		let DelRoleInfo = await db.collection('admin-role').doc(_id).remove()
		ReturnData.msg='删除成功~'
		return ReturnData
	}catch(e){
		ReturnData.code=500
		ReturnData.msg='服务器错误~'
		return ReturnData
	}
}